﻿//-----------------------------------------------------------------------
// <copyright file="AsADistributorAdministratorIShoudAccessUserListSeeNoneCreateANewUserAccessUserListAndSeeOne.cs" company="OOHM PROCESSAMENTO DE DADOS LTDA.">
//     Microsoft Public License (MS-PL) This license governs use of the accompanying
//     software. If you use the software, you accept this license. If you do not
//     accept the license, do not use the software. 1. Definitions The terms "reproduce,"
//     "reproduction," "derivative works," and "distribution" have the same meaning
//     here as under U.S. copyright law. A "contribution" is the original software,
//     or any additions or changes to the software. A "contributor" is any person
//     that distributes its contribution under this license. "Licensed patents"
//     are a contributor's patent claims that read directly on its contribution.
//     2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license,
//     including the license conditions and limitations in section 3, each contributor
//     grants you a non-exclusive, worldwide, royalty-free copyright license to
//     reproduce its contribution, prepare derivative works of its contribution,
//     and distribute its contribution or any derivative works that you create.
//     (B) Patent Grant- Subject to the terms of this license, including the license
//     conditions and limitations in section 3, each contributor grants you a non-exclusive,
//     worldwide, royalty-free license under its licensed patents to make, have
//     made, use, sell, offer for sale, import, and/or otherwise dispose of its
//     contribution in the software or derivative works of the contribution in
//     the software. 3. Conditions and Limitations (A) No Trademark License- This
//     license does not grant you rights to use any contributors' name, logo, or
//     trademarks. (B) If you bring a patent claim against any contributor over
//     patents that you claim are infringed by the software, your patent license
//     from such contributor to the software ends automatically. (C) If you distribute
//     any portion of the software, you must retain all copyright, patent, trademark,
//     and attribution notices that are present in the software. (D) If you distribute
//     any portion of the software in source code form, you may do so only under
//     this license by including a complete copy of this license with your distribution.
//     If you distribute any portion of the software in compiled or object code
//     form, you may only do so under a license that complies with this license.
//     (E) The software is licensed "as-is." You bear the risk of using it. The
//     contributors give no express warranties, guarantees or conditions. You may
//     have additional consumer rights under your local laws which this license
//     cannot change. To the extent permitted under your local laws, the contributors
//     exclude the implied warranties of merchantability, fitness for a particular
// </copyright>
//-----------------------------------------------------------------------
namespace AbstractSaaSTemplate.Utility.Tests.UI.Web.Behaviour.Tenant{    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Mvc;
    using Domain.Models.Entities;
    using AbstractSaaSTemplate.Domain.Models.Enumerators;
    using AbstractSaaSTemplate.Kernel.Factories;
    using AbstractSaaSTemplate.UI.Web.Controllers;
    using AbstractSaaSTemplate.UI.Web.Models.User;
    using AbstractSaaSTemplate.Utility.Tests.UI.Utilities;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    /// <summary>
    /// @13919625
    /// Como Administrador de Distribuidor, eu deveria ser capaz de acessar a
    /// função de acesso controlado "Gerenciamento de Usuários" e visualizar
    /// uma lista de tenants vazia e, posteriormente, acessar a função de
    /// acesso controlado "Criação ou Edição de Usuário", criar um Usuário
    /// e, após este processo, receber este Usuário cadastrado na função
    /// controlada "Gerenciamento de Usuários".
    /// </summary>
    [TestClass]
    public class TestFor0013919645
    {
        #region Properties
        
        /// <summary>
        /// Gets or sets the Tenant controller which will be used in tests.
        /// </summary>
        private UserController UserController { get; set; }

        #endregion

        #region Setup

        /// <summary>
        /// This method initializes controllers and dependencies for run tests.
        /// </summary>
        [TestInitialize]
        public void Setup()
        {
            TestFor0013453151.EnsureInstallationIsComplete();
            
            var factory = new ApplicationFactory();

            this.UserController = factory.CreateControllerFor<UserController>();
        }

        #endregion

        /// <summary>
        /// @13919625
        /// Como Administrador de Distribuidor, eu deveria ser capaz de acessar a
        /// função de acesso controlado "Gerenciamento de Usuários" e visualizar
        /// uma lista de tenants vazia e, posteriormente, acessar a função de
        /// acesso controlado "Criação ou Edição de Usuário", criar um Usuário
        /// e, após este processo, receber este Usuário cadastrado na função
        /// controlada "Gerenciamento de Usuários".
        /// Passos da Mímica --------------------------------------------------
        /// 1.  Executa o Logon com usuário pertinente
        ///     Deve assegurar:
        ///     1.1) Que o usuário está logado (activeUser)
        /// 2.  Acessar a lista de usuarios. (User/ListUsers)
        ///     Deve assegurar:
        ///     2.1) A lista é vazia.
        /// 3.  Criar um usuário.
        ///     Deve assegurar:
        ///     3.2) Que o usuario foi criado.
        /// 4.  Editar o usuario recém criado.
        ///     Deve assegurar:
        ///     4.1) Que o usuario editado é o mesmo recém criado.
        ///     4.2) Que os campos alterados foram realmente alterados.
        /// 5.  Acessar a lista de usuários. (tenant/ListUsers)
        ///     Deve assegurar:
        ///     5.1) Que existe um User na listagem.
        ///     5.2) Que o tenant seja o mesmo User que foi criado anteriormente.
        /// </summary>
        [TestMethod]
        public void AsADistributorAdministratorIShoudAccessUserListSeeNoneCreateANewUserAccessUserListAndSeeOne()
        {
            /* =========================================================
             * EXECUÇÃO DA MÍMICA
             * =========================================================
             * Os procedimentos executados à seguir são uma mímica dos
             * procedimentos executados pelos usuários no uso real do sistema.
             * ========================================================= */

            // 1)
            this.LogOnAndAssertActiveUser();

            // 2)
            this.AssertThatThereAreNoUsers();
            
            // 3)
            var createdUser = this.CreateUserAndEnsureItExists();

            // 4)
            var editedUser = this.EditUserAndEnsureThatItWasEdited(createdUser);

            // 5)
            this.AssertThatRecentlyCreatedUserIsShowedInListUsers(editedUser);
        }

        /// <summary>
        /// 1.  Executa o Logon com usuário pertinente
        ///     Deve assegurar:
        ///     1.1) Que o usuário está logado (activeUser)
        /// </summary>
        private void LogOnAndAssertActiveUser()
        {
            var distributorAdmin = this.UserController.RepositoryForMembership.GetUsersByRole(
                AccessLevels.Distributor,
                AccessRoles.Administrator).FirstOrDefault();

            this.UserController.MockForTesting("LogOn", HttpVerbs.Post);
            this.UserController.LogOn(
                new LogOnForm()
                {
                    Login = distributorAdmin.Credentials.Login,
                    Password = distributorAdmin.Credentials.RetrievePassword()
                },
                string.Empty);
            
            var activeUser = this.UserController.ServiceForMembership.ActiveUser;
            Assert.IsNotNull(activeUser);
        }
        
        /// <summary>
        /// 2.  Acessar a lista de usuarios. (User/ListUsers)
        ///     Deve assegurar:
        ///     2.1) A lista é vazia.
        /// </summary>
        private void AssertThatThereAreNoUsers()
        {
            // Mock controller for testing.
            this.UserController.MockForTesting("ListUsers", HttpVerbs.Get);

            // Perform list of users.
            var actionResult = this.UserController.ListUsers();

            // Assert that result is view result.
            Assert.IsInstanceOfType(actionResult, typeof(ViewResult));

            // Get view result.
            var viewResult = actionResult as ViewResult;

            // Assert that model passed in action is an IEnumerable<Tenant>.
            Assert.IsInstanceOfType(viewResult.Model, typeof(IEnumerable<Domain.Models.Entities.User>));

            // Get model,
            var model = viewResult.Model as IEnumerable<Domain.Models.Entities.User>;
            Assert.IsNotNull(model);

            var usersNotFromInstalationInModel = model
                .Where(d =>
                    d.EmailAddress != TestFor0013453151.StaffEmail &&
                    d.EmailAddress != TestFor0013919625.TenantAdministratorEmailAddress)
                .ToArray();

            // Assert that exists 0 users, as we have not created one yet.
            Assert.AreEqual(0, usersNotFromInstalationInModel.Count());
        }

        /// <summary>
        /// 3.  Criar um usuário.
        ///     Deve assegurar:
        ///     3.2) Que o usuario foi criado.
        /// </summary>
        /// <returns>The user created.</returns>
        private User CreateUserAndEnsureItExists()
        {
            // data for create a tenant
            var model = new CreateOrEditUserForm(AccessRoles.Operator);
            model.FirstName = "Suzana";
            model.LastName = "Vieira";
            model.CultureName = "en-US";
            model.Login = "suzana.vieira";
            model.Password = "823921mg9";
            model.EmailAddress = "suzana.vieira@site.com";
            model.IsDisabled = false;

            // Clear model state for perform new test.
            this.UserController.ModelState.Clear();

            // Perform create tenant.
            var actionResult = this.UserController.CreateOrEditUser(null, model);

            // Check validation.
            Assert.IsTrue(this.UserController.ModelState.IsValid);

            // Assert that action return redirect.
            Assert.IsInstanceOfType(actionResult, typeof(RedirectToRouteResult));

            // Get user from users repository.
            var users = this.UserController
                .RepositoryForMembership
                .GetUsers(UserController.ServiceForMembership.ActiveUser.AccessLevel)
                .Where(d => d.EmailAddress == model.EmailAddress)
                .Where(d => d.FirstName == model.FirstName)
                .Where(d => d.LastName == model.LastName)
                .ToList();

            // Check if tenant was created.
            Assert.IsTrue(users.Count() == 1);

            return users.FirstOrDefault();
        }

        /// <summary>
        /// 4.  Editar o user recém criado.
        ///     Deve assegurar:
        ///     4.1) Que o user editado é o mesmo recém criado.
        ///     4.2) Que os campos alterados foram realmente alterados.
        /// </summary>
        /// <param name="createdUser">The recently created user.</param>
        /// <returns>The user edited.</returns>
        private User EditUserAndEnsureThatItWasEdited(User createdUser)
        {
            // data for edit a user
            var model = new CreateOrEditUserForm();
            long id = createdUser.Id;
            model.FirstName = "Selene";
            model.LastName = "Costa";
            model.CultureName = "pt-BR";
            model.Login = "selene.costa";
            model.Password = "10101010";
            model.EmailAddress = "selene.costa@site.com";
            model.IsDisabled = true;

            // Clear model state for perform new test.
            this.UserController.ModelState.Clear();

            // Perform edit.
            var actionResult = this.UserController.CreateOrEditUser(id, model);

            // Check validation.
            Assert.IsTrue(this.UserController.ModelState.IsValid);

            // Assert that action return redirect.
            Assert.IsInstanceOfType(actionResult, typeof(RedirectToRouteResult));

            // Get tenants from tenant repository and check if recently created exists.
            var user = this.UserController
                .RepositoryForMembership
                .GetUserById(id);

            // Check if user was edited.
            Assert.IsNotNull(user);

            // Check if tenant was not duplicated.
            Assert.AreEqual<string>(model.FirstName, user.FirstName);
            Assert.AreEqual<string>(model.LastName, user.LastName);
            Assert.AreEqual<string>(model.EmailAddress, user.EmailAddress);
            Assert.AreEqual<string>(model.Login, user.Credentials.Login);
            Assert.AreEqual<string>(model.Password, user.Credentials.RetrievePassword());
            Assert.AreEqual<string>(model.CultureName, user.Culture.Name);
            Assert.AreEqual<bool>(model.IsDisabled, user.IsDisabled);
            
            return user;
        }

        /// <summary>
        /// 5.  Acessar a lista de users licenciados. (Users/ListUsers)
        ///     Deve assegurar:
        ///     5.1) Que existe um user na listagem.
        ///     5.2) Que o user seja o mesmo tenant que foi criado anteriormente.
        /// </summary>
        /// <param name="editedUser">The edited user.</param>
        private void AssertThatRecentlyCreatedUserIsShowedInListUsers(User editedUser)
        {
            // Mock controller for testing.
            this.UserController.MockForTesting("ListUsers", HttpVerbs.Get);

            // Perform list of tenants.
            var actionResult = this.UserController.ListUsers();

            // Assert that result is view result.
            Assert.IsInstanceOfType(actionResult, typeof(ViewResult));

            // Get view result.
            var viewResult = actionResult as ViewResult;

            // Assert that model passed in action is an IEnumerable<Tenant>.
            Assert.IsInstanceOfType(viewResult.Model, typeof(IEnumerable<Domain.Models.Entities.User>));

            // Get model,
            var model = viewResult.Model as IEnumerable<Domain.Models.Entities.User>;
            Assert.IsNotNull(model);

            var usersWhoAreNotTheDistributorAdminInModel = model
                .Where(d =>
                    d.EmailAddress != TestFor0013453151.StaffEmail &&
                    d.EmailAddress != TestFor0013919625.TenantAdministratorEmailAddress)
                .ToArray();

            // Assert that exists 1 tenant.
            Assert.AreEqual(1, usersWhoAreNotTheDistributorAdminInModel.Count());

            // Get tenant.
            var user = usersWhoAreNotTheDistributorAdminInModel.FirstOrDefault();

            // Assert that listed tenant and edited tenant are same.
            Assert.AreEqual<string>(
                user.Credentials.Login,
                editedUser.Credentials.Login);
        }
    }
}


